package cn.edu.nit.sys.mapper;

import cn.edu.nit.sys.entity.Message;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * @Author xiaobai
 * @Date 2022/11/2 20:15
 * @Version 1.0.0
 */
public interface MessageMapper extends BaseMapper<Message> {

    @Select("SELECT a.create_time, a.type, a.fid, a.user_id, b.avatar, b.nickname FROM sys_notice_log a " +
            "left join sys_user b on a.target = b.id where a.target = #{uid} ORDER BY a.create_time desc")
    Page<Map<String, String>> getSysMessageList(Page<Map<String, String>> page, String uid);

    @Update("update sys_notice_log set status = '1' where target = #{id}")
    int changeReadStatus(String id);

    @Select("select a.id, a.source, a.body, a.send_time, b.nickname, b.avatar from sys_message a " +
            "left join sys_user b on a.source = b.id where a.target = #{userId} and a.status = '0' order by a.send_time asc")
    List<Map<String, String>> getNoReadMessage(String userId);

    @Select("select (select count(id) from sys_notice_log where target = #{id} and status = '0') as badge, " +
            "a.type, b.nickname from sys_notice_log a " +
            "left join sys_user b on a.target = b.id where a.target = #{id} and a.status = '0' limit 1")
    List<Map<String, Object>> notReadNotice(String id);

    @Select("select a.source, b.nickname, b.avatar from sys_message a " +
            "left join sys_user b on a.source = b.id where status = '0' and a.target = #{id} GROUP BY source")
    List<Map<String, Object>> getMessageUsers(String id);

    @Select("select id, body as label, " +
            "(select count(id) from sys_message where status = '0' and source = #{source} and target = #{id}) as badge " +
            "from sys_message where status = '0' and source = #{source} and target = #{id} ORDER BY send_time desc limit 1")
    Map<String, Object> getUserMessage(String id, String source);


    @Select("select id, target, source, body, " +
            "if(DATEDIFF(now(), send_time) < 1, DATE_FORMAT(send_time,'%H:%i'), DATE_FORMAT(send_time,'%Y-%m-%d %H:%i')) as time, " +
            "if(source = #{userId1}, true, false) as isMy from sys_message " +
            "where target in(#{userId1}, #{userId2}) and source in(#{userId1}, #{userId2}) order by send_time asc")
    Page<Map<String, String>> getMessageList(Page<Map<String, String>> page, String userId1, String userId2);

    @Update("update sys_message set status = '1' where target = #{target} and source = #{source}")
    int readMessage(String target, String source);
}
